
# 使用TimedJSONWebSignatureSerializer可以生成带有有效期的token
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData

from meiduo import settings


def generate_save_user_token(openid):
    # serializer = Serializer(秘钥, 有效期秒)
    serializr = Serializer(settings.SECRET_KEY, expires_in=3600)
    data = {'openid':openid}
    # dumps: serializer.dumps(数据), 返回bytes类型
    token = serializr.dumps(data)
    return  token.decode()

# 准备序列化
def check_save_user_token(access_token):
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY,expires_in=3600)
    try:
        # loads: 返回json
        data = serializer.loads(access_token)
        # 检验token
        # 验证失败，会抛出itsdangerous.BadData异常
    except BadData:
        return  None

    return data.get('openid')


